package com.xinlong.shop.api.member;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinlong.shop.api.common.BuyerBaseController;
import com.xinlong.shop.core.member.entity.dto.MemberListDTO;
import com.xinlong.shop.core.member.entity.vo.MemberLoginVO;
import com.xinlong.shop.core.member.service.IMemberBalanceDetailService;
import com.xinlong.shop.core.member.service.IMemberService;
import com.xinlong.shop.core.member.service.IMemberWithdrawalService;
import com.xinlong.shop.framework.common.R;
import com.xinlong.shop.framework.core.entity.Member;
import com.xinlong.shop.framework.security.constant.SecurityConstants;
import com.xinlong.shop.framework.security.util.TokenUtil;
import com.xinlong.shop.framework.util.StringUtil;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Sylow
 * @Description
 * @Date: Created in 00:18 2022/12/26
 */
@RestController
@RequestMapping("/buyer/member")
public class BuyerMemberController extends BuyerBaseController {

    private final IMemberBalanceDetailService memberBalanceDetailService;
    private final IMemberWithdrawalService memberWithdrawalService;

    public BuyerMemberController(IMemberService memberService, TokenUtil tokenUtil, IMemberBalanceDetailService memberBalanceDetailService, IMemberWithdrawalService memberWithdrawalService) {
        super(memberService,tokenUtil);
        this.memberBalanceDetailService = memberBalanceDetailService;
        this.memberWithdrawalService = memberWithdrawalService;
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public R login(String userName, String password, String code, Integer loginType){
        // userName 前端目前传递的是手机号，也支持用户名
        if (!StringUtil.vaildMobile(userName)) {
            return R.error("手机格式不正确");
        }
        MemberLoginVO memberLoginVO = null;
        //1是验证码登录
        if (loginType.intValue() == 1) {
            boolean result = this.memberService.verifySmsCode(userName, "login", code);
            if (result) {
                memberLoginVO = this.memberService.login(userName, null, false);
            } else {
                return R.error("验证码错误");
            }
        } else {
            memberLoginVO = this.memberService.login(userName, password, true);
        }

        if (memberLoginVO == null || StrUtil.isBlank(memberLoginVO.getToken())) {
            return R.error("登录失败,错误的用户名或密码");
        } else {

            if (memberLoginVO.getMember().getStatus().intValue() != 0) {
                return R.error("账号已被禁用");
            }

            // 记住我功能后期再开发，现在默认就是记住
            String refreshToken = this.memberService.generateRefreshToken(userName, true);
            memberLoginVO.setRefreshToken(refreshToken);
        }
        return R.success("登录成功", memberLoginVO);
    }

    @RequestMapping(value = "/token", method = RequestMethod.GET)
    public R refreshToken(String refreshToken, String userName){
        if (StrUtil.isNotBlank(refreshToken) && StrUtil.isNotBlank(userName)) {
            refreshToken = refreshToken.replace(SecurityConstants.TOKEN_PREFIX, "");
            String tokenUserName = tokenUtil.getUserNameFromToken(refreshToken);
            // 判断用户名与token是否匹配
            if (!userName.equals(tokenUserName)) {
                return R.success("用户名与refreshToken不匹配");
            }
            String token = this.memberService.generateRefreshToken(userName, false);
            return R.success("操作成功", token);
        } else {
            return R.error("token和用户名不能为空");
        }
    }

    /**
     * 获取会员信息，这里暂时不做权限控制，任何登录会员都可调用
     * @param memberId
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public R info(Integer memberId){
        if (memberId == null) {
            return R.error("会员Id不能为空");
        }
        MemberListDTO member = this.memberService.findMemberDTOById(memberId);
        return R.success(member);
    }

    /**
     * 发送短信验证码 暂时不添加验证码逻辑
     * @param phone
     * @return
     */
    @RequestMapping(value = "/send-code", method = RequestMethod.GET)
    public R sendCode(String phone, String scene){
        if (!StringUtil.vaildMobile(phone)) {
            return R.error("手机格式不正确");
        }
        // 暂时有 注册 register 改密码password 登录login
        boolean result = this.memberService.sendSmsCode(phone, scene);
        if (!result) {
            return R.error("短信发送失败，请重试");
        }

        return R.success("发送成功");
    }


    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public R register(String phone, String password, String code, String inviteMemberNo){
        if (!StringUtil.vaildMobile(phone)) {
            return R.error("手机格式不正确");
        }

        if(password == null || password.length() < 6 || password.length() >20){
            return R.error("密码长度在6-20位");
        }
        if (code == null || code.length() != 6) {
            return R.error("验证码长度不正确");
        }
        if (StrUtil.isBlank(inviteMemberNo)) {
            return R.error("没有邀请人");
        }

        boolean result = this.memberService.verifySmsCode(phone, "register", code);
        if (!result) {
            return R.error("验证码错误");
        }

        this.memberService.register(phone, password, inviteMemberNo);
        return R.success("注册成功");
    }


    // 被邀请人会员列表
    @RequestMapping(value = "/invitee-list", method = RequestMethod.GET)
    public R inviteeList(Integer current, Integer size,  @RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){
        IPage<Member> page = new Page<>(current, size);
        Member member = getMember(token);

        //page.addOrder(new OrderItem("sort", true));
        page = this.memberService.inviteePage(member.getId(), page);
        return R.success("操作成功", page);
    }

    // 会员余额
    @RequestMapping(value = "/balance", method = RequestMethod.GET)
    public R inviteeList(@RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){

        Member member = getMember(token);
        return R.success("操作成功", member.getBalance());
    }

    // 获取用户 可提现金额、累计收益、累计提现
    @RequestMapping(value = "/balance-info", method = RequestMethod.GET)
    public R balanceInfo(@RequestHeader(value = SecurityConstants.TOKEN_HEADER, required = true) String token){

        Member member = getMember(token);
        BigDecimal incomeTotal = this.memberBalanceDetailService.findBalanceTotalByMemberId(member.getId());
        BigDecimal withdrawalTotal = this.memberWithdrawalService.findTotalByMemberId(member.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("balance", member.getBalance());
        map.put("incomeTotal", incomeTotal);
        map.put("withdrawalTotal",withdrawalTotal);

        return R.success("操作成功", map);
    }

    @RequestMapping(value = "/nickname", method = RequestMethod.GET)
    public R getNickname(String mobile) {
        if (!StringUtil.vaildMobile(mobile)) {
            return R.error("手机格式不正确");
        }
        Member member = this.memberService.findByMobile(mobile);
        if (member == null) {
            return R.error("会员不存在");
        }
        return R.success(member.getNickname());
    }

}
